package com.hunsy.fileupload.DAO;

import com.hunsy.fileupload.BqConf;
import com.hunsy.fileupload.Tools.Uniqid;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import org.apache.tomcat.jdbc.pool.DataSource;

import java.util.List;


/**
 * Created by studio on 2017/6/7.
 */

@Repository
public class ProductPropertyDAO {

    private JdbcTemplate jdbcTemplate;

    public ProductPropertyDAO(){

        DataSource ds = new DataSource();

        ds.setDriverClassName(BqConf.DRIVER_CLASS_NAME);
        ds.setUrl(BqConf.DATASOURCE_URL);
        ds.setUsername(BqConf.DATASOURCE_USERNAME);
        ds.setPassword(BqConf.DATASOURCE_PASSWORD);

        jdbcTemplate = new JdbcTemplate(ds);
    }

    /**
     *
     * @param product_id 产品id
     * @param properties 0为数据库字段名,1为excel字段名
     * @param list 标识名,显示名称,数据类型,分别作为property,display_name,type (多条记录可批量插入)
     * @return
     */
    public int insert(String product_id, String[] properties, List<JSONObject> list){

        String sql = "insert into product_property(id," + properties[0] + ",product_id) " +
                "values ";
        String value = "";
        String key[] = properties[1].split(",");
        int success_count = 0;   //导入成功次数

        for (JSONObject json: list
             ) {
            if (!value.equals("")){
                value+=",";
            }

            try {
                value += "('"+ Uniqid.getId()+"'";

                for(int i=0;i<key.length;i++){
                    value += ",'"+json.getString(key[i])+"'";
                }

                value += ",'"+product_id+"')";
                success_count++;
            } catch (JSONException e) {
                e.printStackTrace();
                if (!value.equals("")){
                    value = value.substring(0,value.length()-1);
                }
            }
        }

        jdbcTemplate.execute(sql+value);
        return success_count;
    }

}
